package com.baixiaowen.xiaoaointerview.并发基础篇;

import java.util.LinkedList;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 生产者消费者问题
 *
 * @author Baixiaowen
 */
public class ProducerCustomerModel {
    final static int MAX = 10;
    // 生产队列
    LinkedList<Integer> queue = new LinkedList<>();

    ReentrantLock lock = new ReentrantLock();
    Condition full = lock.newCondition();
    Condition empty = lock.newCondition();


    // 模拟生产成本
    int readDate() throws InterruptedException {
        Thread.sleep((long) Math.random() * 1000);
        return (int) Math.floor(Math.random());
    }

    // Producer
    public void readDb() throws InterruptedException {
        lock.lock();
//        synchronized (queue) {
            if (queue.size() == MAX) {
                full.await();
//                queue.wait();
                return;
            }

            int data = readDate(); // 1s
            if (queue.size() == 1) {
//                queue.notifyAll();
                empty.signalAll();
            }
            queue.add(data);
//        }
        lock.unlock();
    }

    // Consumer
    public void calculate() throws InterruptedException {
        lock.lock();
//        synchronized (queue) {
            if (queue.size() == 0) {
                empty.await();
//                queue.wait();
                return;
            }

            int data = readDate(); // 1s
            queue.remove();
            System.err.println("queue-size: " + queue.size());
            if (queue.size() == MAX - 1) {
                full.signalAll();
//                queue.notifyAll();
            }
            data *= 100;
//        }
        lock.unlock();

    }

    // P0 P1
    // C0
    // PO P1 (sleeping) C0 -> notify (P0 | P1)
    // CO P0 (sleeping) ->
    public static void main(String[] args) {
        ProducerCustomerModel p = new ProducerCustomerModel();
        for (int i = 0; i < 100; i++) {
            new Thread(() -> {
                while (true) {
                    try {
                        p.readDb();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }

        for (int i = 0; i < 100; i++) {
            new Thread(() -> {
                while (true) {
                    try {
                        p.calculate();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }

}
